package cn.edu.swu.auth;

import cn.edu.swu.core.AbstractRepo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/user/*")
public class UserController extends HttpServlet {

    private UserRepo userRepo = null;
    private final ObjectMapper mapper = new ObjectMapper();

    @Override
    public void init() {
        userRepo = new UserRepo();
        try {
            userRepo.testConnection();
        } catch (SQLException e) {
            e.printStackTrace(); // 如果连接失败,会打印异常信息
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.methodRoute(request, response);
    }

    private void methodRoute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        String method = uri.substring(uri.lastIndexOf("/") + 1);

        System.out.println("Request URI: " + uri);
        System.out.println("Request Method: " + method);

        try {
            if (method.equals("register")) {
                this.register(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace(); // 输出详细错误信息到控制台
            this.getServletContext().log("服务器错误: " + e.getMessage());
            responseJson(response, false, "服务器错误: " + e.getMessage());
        }
    }



    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 密码加密
        String encryptedPassword = DigestUtils.md5Hex(password);

        UserMsg user = new UserMsg();
        user.setUsername(username);
        user.setUserPwd(encryptedPassword);

        if (isUsernameAvailable(username)) {
            if (insertUser(user)) {
                responseJson(response, true, "注册成功");
            } else {
                responseJson(response, false, "注册失败，请稍后再试");
            }
        } else {
            responseJson(response, false, "用户名已被占用，请选择其他用户名");
        }
    }

    private boolean isUsernameAvailable(String username) throws SQLException {
        System.out.println("isUsernameAvailable");
        String sql = "SELECT COUNT(*) FROM usermsg WHERE username = ?";
        return userRepo.query(sql, ps -> {
            try {
                ps.setString(1, username);
                ResultSet rs = ps.executeQuery();
                return rs.next() && rs.getLong(1) == 0;
            } catch (SQLException e) {
                throw new RuntimeException("Database error in isUsernameAvailable: " + e.getMessage());
            }
        });
    }

    private boolean insertUser(UserMsg user) throws SQLException {
        System.out.println("insertUser");
        String sql = "INSERT INTO usermsg (username, userPwd) VALUES (?, ?)";
        return userRepo.execute(sql, ps -> {
            try {
                ps.setString(1, user.getUsername());
                ps.setString(2, user.getUserPwd());
                int rowsAffected = ps.executeUpdate();
                return rowsAffected > 0;
            } catch (SQLException e) {
                throw new RuntimeException("Database error in insertUser: " + e.getMessage());
            }
        });
    }

    private void responseJson(HttpServletResponse response, boolean success, String message) throws IOException {
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        try {
            mapper.writeValue(response.getWriter(), new RegistrationResponse(success, message));
        } catch (JsonProcessingException e) {
            this.getServletContext().log("Error serializing JSON response: " + e.getMessage());
            response.getWriter().write("{\"success\":false,\"message\":\"服务器错误: JSON序列化失败\"}");
        }
    }



    private static class RegistrationResponse {
        private boolean success;
        private String message;

        public RegistrationResponse(boolean success, String message) {
            this.success = success;
            this.message = message;
        }

        // Getter methods for Jackson serialization
        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
    }
}